StartPage.ClosedTabs=(function(){return{
	items: null
	
	,populate: function(){
		if (!this.items){ this.refresh(); return; }
		var container=$('#startpage-closed', gBrowser.contentDocument);
		container.html(this.items.join(''))
	}
	
	,getIcon: function(aURI){
		var favSvc = Cc["@mozilla.org/browser/favicon-service;1"].getService(Ci.nsIFaviconService), icon; 
		if (!aURI) icon=favSvc.defaultFavicon.spec;
		else {
			icon = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newURI(aURI,null,null);
			if (icon) icon=favSvc.getFaviconLinkForIcon(icon).spec;
			else icon=aURI;
		}
		return icon;
	}
	
	,refresh: function(){
		//if (gBrowser.currentURI.spec.indexOf('chrome://startpage')===false && gBrowser.currentURI.spec!='about:blank') return;
		var ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore), i=0, n=0, items=[], unArr=[];
		if (ss.getClosedTabCount(window)){
			var undoItems = eval("(" + ss.getClosedTabData(window) + ")"), uIl=undoItems.length, icon, url, title;
			for(i = n = 0; i < uIl; i++){
				title=undoItems[i].title;
				if (unArr.in_array(title)>=0) continue; // check if already on the list
				var tabData = undoItems[i].state, activeIndex = (tabData.index || tabData.entries.length) - 1;
				if (activeIndex >= 0 && tabData.entries[activeIndex]) url=tabData.entries[activeIndex].url;
				icon = this.getIcon(undoItems[i].image); 
				items.push('<li><a href="'+url+'"><img src="'+icon+'" />'+title+'</a></li>');
				unArr.push(title);
				if (++n>=10) break;
			}
		}
		if (n<10) {
			if (n>0&&n<9){ items.push('<span class="separator"></span>'); n++; } // increase i to make space for separator
			items.push(this.getRecentHistory(10-n));
		}
		this.items=items;
		this.populate();
	}
	
	,getRecentHistory: function(ile){
		var db, sql
		if (Ci.nsPIPlacesDatabase) db = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsPIPlacesDatabase).DBConnection;
		sql = db.createStatement(
			' SELECT DISTINCT moz_places.id, moz_places.title, moz_places.url, moz_favicons.url FROM moz_historyvisits '+
			' LEFT JOIN moz_places ON moz_places.id=moz_historyvisits.place_id'+
			' LEFT JOIN moz_favicons ON moz_places.favicon_id=moz_favicons.id'+
			' WHERE moz_historyvisits.visit_type=1 GROUP BY moz_places.title ORDER BY moz_historyvisits.visit_date DESC LIMIT 0,'+ile
		);
		var id, title, url, icon, items=[], del;
		while(sql.executeStep()){
			id = sql.getString(0);
			title = sql.getString(1);
			url = sql.getString(2);
			icon = this.getIcon(sql.getString(3));
			del='<span title="Remove from list" class="del" id="plc'+id+'" onclick="fireEvent(\'removePlace\',this);return false"></span>';
			items.push('<li>'+del+'<a href="'+url+'"><img src="'+icon+'" />'+title+'</a>'+'</li>');
		}
      sql.reset(); sql.finalize(); // Close the query incase there's more pages than we can show
		return items.join('');
	}
}}());
